/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */

Ext.namespace("Org");


/**
 * CouncilGroup edit dialog.
 *
 * @param config the configuration.
 */

Org.CouncilGroupDialog = function(config) {
	Org.CouncilGroupDialog.superclass.constructor.call(this, config);
};

Ext.extend(Org.CouncilGroupDialog, Ext.Window, {

	initComponent: function() {

		Ext.apply(this, {
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-councilgroup-add',
			title: MSG['councilgroup.new'],
			bodyStyle:'padding:5px'
		});

		this.items = new Ext.FormPanel({
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'id',
				value: 0
			}, {
				xtype: 'hidden',
				name: 'organization',
				value: Main.app.getUser().organization.id
			}, {
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['councilgroup.name'],
				maxLength: 40,
				allowBlank: false
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});


		Org.CouncilGroupDialog.superclass.initComponent.call(this);
	},

	onSave: function() {
		var theForm = this.items.items[0].getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onCancel: function() {
		this.close();
	},

	onSaveSuccess: function(/*form, action*/) {
		this.close();
		notifySuccess(MSG['user.update'], MSG['update.success']);
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['user.update'], MSG['update.error']);
	}

});



/**
 * Qualification Checks Paths associated.
 *
 * @param config the configuration.
 */
Org.CouncilgroupCheckDelete = function(config) {
	Org.CouncilgroupCheckDelete.superclass.constructor.call(this, config);
};

Ext.extend(Org.CouncilgroupCheckDelete, Ext.Window, {

	gridCheck: null,

	checkStore: null,

	waitDlg: null,

	data: null,

	searchPanel: null,

	initComponent: function() {
		Ext.apply(this, {
			layout: 'border',
			width: '70%',
			height: 400,
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-councilgroup-find',
			title: MSG['councilgroup.checks'],
			bodyStyle:'padding:5px'
		});

		// Store
		this.checkStore = new Ext.data.JsonStore({
			root: 'results',
			fields:[
				{name: 'id', type: 'int'},
				{name: 'name', type: 'string'},
				{name: 'councils', type: 'int'}
			],
			data: Ext.util.JSON.decode(this.data)
		});

		//Custom column plugin for checkcolumn
		var elementsCheckBox = new Ext.grid.CheckboxSelectionModel();

		// Grid
		this.gridCheck = new Ext.grid.GridPanel({
			region: 'center',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				elementsCheckBox,
				{header: MSG['councilgroup.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['councilgroup.name'], dataIndex: 'name', width: 70, sortable: true},
				{header: MSG['councils'], dataIndex: 'councils', width: 20, sortable: true}
			]),
			sm: elementsCheckBox,
			store: this.checkStore,
			buttons: [{
				text: MSG['button.validate'],
				iconCls: 'icon-ok',
				handler: this.onRemoveSelected,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onClose,
				scope: this
			}]
		});
		this.items = [this.gridCheck];
		Org.CouncilgroupCheckDelete.superclass.initComponent.call(this);
	},
	
	onRemoveSelected: function(){
		var selections = this.gridCheck.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			for (var i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/delete.json',
				success: function(){
						notifySuccess(MSG['delete'], MSG['delete.success']);
				},
				failure: function(){
					notifyError(MSG['delete'], MSG['delete.error']);
				},
				params: { elements: elements }
			});
		};

		this.searchPanel.onReset();

		this.onClose();
	},

	onClose: function(){
		this.close();
	}
});




/**
 *	CouncilGroup search panel.
 *
 * @param config the configuration.
 */
Org.CouncilGroupSearchPanel = function(config) {
	Org.CouncilGroupSearchPanel.superclass.constructor.call(this, config);
};

Ext.extend(Org.CouncilGroupSearchPanel, Ext.Panel, {

	searchForm: null,

	resultsStore: null,

	pageToolbar: null,

	resultsGrid: null,

	editForm: null,

	waitDlg: null,

	initComponent: function() {
		this.layout = 'border';
		this.title = MSG['councilgroup.title'];
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-councilgroup';

		// Tools
		this.tools = [{
			id: 'close',
			handler: this.onClose,
			scope: this
		}];

		// Search form
		this.searchForm = new Ext.FormPanel({
			region: 'west',
			split: true,
			collapsible: true,
			title: MSG['councilgroup.title'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['councilgroup.name'],
				maxLength: 40
			}, {
				xtype: 'hidden',
				name: 'organization',
				value: Main.app.getUser().organization.id
			}],
			buttons: [{
				text: MSG['button.search'],
				iconCls: 'icon-search',
				handler: this.onSearch,
				scope: this
			}, {
				text: MSG['button.reset'],
				iconCls: 'icon-cancel',
				handler: this.onReset,
				scope: this
			}]
		});

		// Store
		this.resultsStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			fields: ['id', 'name']
		});
		this.resultsStore.on("beforeload",
				function() {
					this.waitDlg = Ext.Msg.wait(MSG['wait.title'], MSG['wait.text']);
					this.resultsStore.baseParams = this.searchForm.getForm().getRawValues();
				}, this);
		this.resultsStore.on("load",
				function() {
					if(this.waitDlg) {
						this.waitDlg.hide();
					}
				}, this);

		// Pagination toolbar
		this.pageToolbar = new Ext.PagingToolbar({
			store: this.resultsStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin(MSG['page.size'])],
			items:[
				'-', {
					text: MSG['button.remove'],
					iconCls: 'icon-remove',
					handler: this.onCheckRemoveSelected,
					scope: this
				}
			]
		});

		// Grid
		this.resultsGrid = new Ext.grid.GridPanel({
			title: MSG['result.title'],
			region: 'center',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				{header: MSG['councilgroup.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['councilgroup.name'], dataIndex: 'name', width: 100, sortable: true}
			]),
			store: this.resultsStore,
			bbar: this.pageToolbar
		});

		// Editor
		this.editForm = new Ext.FormPanel({
			region: 'east',
			split: true,
			collapsible: true,
			collapsed: true,
			title: MSG['button.new'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'id',
				value: 0
			}, {
				xtype: 'hidden',
				name: 'organization',
				value: Main.app.getUser().organization.id
			}, {
				xtype: 'textfield',
				name: 'name',
				fieldLabel:  MSG['councilgroup.name'],
				maxLength: 40,
				allowBlank: false
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});

		this.items = [this.searchForm, this.resultsGrid, this.editForm];

		this.pageToolbar.doLoad(0);

		this.resultsGrid.on("rowclick", this.onSelected, this);

		Org.CouncilGroupSearchPanel.superclass.initComponent.call(this);
	},

	onClose: function() {
		Main.app.addPanel(null);
	},

	onSearch: function() {
		this.editForm.collapse();
		this.pageToolbar.doLoad(0);
	},

	onReset: function() {
		this.searchForm.getForm().reset();
		this.pageToolbar.doLoad(0);
	},

	onSelected: function(grid, rowIndex/*, evt*/) {
		this.searchForm.collapse();
		this.editForm.expand();

		var record = grid.getStore().getAt(rowIndex);
		var data = {};
		Ext.apply(data, record.data);
		data.organization = Main.app.getUser().organization.id;

		this.editForm.getForm().loadRecord({data: data});
		this.editForm.setTitle(MSG['edit.title']);		
	},

	onSave: function() {
		var theForm = this.editForm.getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onSaveSuccess: function(/*form, action*/) {
		notifySuccess(MSG['update'], MSG['update.success']);
		this.pageToolbar.onClick("refresh");
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['update'], MSG['update.error']);
	},

	onCancel: function() {
		this.editForm.getForm().reset();
		this.editForm.setTitle(MSG['button.new']);	
	},

	onCheckRemoveSelected: function() {
		var selections = this.resultsGrid.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			for (var i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/checkdelete.json',
				success: function( result/*, request */){
					if (result.responseText){
						var winCheck = new Org.CouncilgroupCheckDelete({data: result.responseText, searchPanel: this});

						winCheck.show();
					}
				},
				failure: function(){
					notifyError(MSG['error'], MSG['check.error']);
				},
				params: { elements: elements },
				scope: this
			});
		}
	},

	getToolbar: function(){
		return this.pageToolbar;
	},

	getEditForm: function(){
		return this.editForm;
	}

});

/**
 * CouncilGroups combo.
 */
Org.CouncilGroupCombo = function(config) {
	Org.CouncilGroupCombo.superclass.constructor.call(this, config);
};

Ext.extend(Org.CouncilGroupCombo, Ext.form.ComboBox, {

	organization: null,

	initComponent: function() {

		this.fieldLabel = MSG['councilgroup.title'];
		if(this.hiddenName == null) {
			this.hiddenName = 'councilgroups';
		}
		this.width = 250;
		this.store = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/councilgroups.json',
			root: 'results',
			fields: ['id', 'name'],
			baseParams: { organization: this.organization.id }
		});
		this.tpl = new Ext.XTemplate(
				'<tpl for="."><div class="search-item">',
				'<h3>{name}</h3>',
				'{id} - {name}',
				'</div></tpl>'
		);

		this.itemSelector = 'div.search-item';
		this.minChars = 2;
		this.typeAhead = false;
		this.valueField = 'id';
		this.displayField = 'name';
		this.triggerAction = 'all';

		this.listeners = {
			blur: function () {
				if (this.getRawValue() == "") {
					this.clearValue();
				}
			}
		};

		Org.CouncilGroupCombo.superclass.initComponent.call(this);
	},

	setValue: function(v) {
		// See https://yui-ext.com/forum/showthread.php?t=20803

		// If the ComboBox hasn't been loaded yet, load it asynchronously
		// before setting the value.
		if (this.mode == 'remote' && this.store.getCount() == 0) {
			this.store.on("load", function () {
				Org.CouncilGroupCombo.superclass.setValue.call(this, v);
			}, this, {single: true});
			this.doQuery(this.allQuery, true);
		} else {
			Org.CouncilGroupCombo.superclass.setValue.call(this, v);
		}
	}

});



/**
 * CouncilGroup to council panel.
 *
 * @param config the configuration.
 */
Org.CouncilGroupToCouncilPanel = function(config) {
	Org.CouncilGroupToCouncilPanel.superclass.constructor.call(this, config);
};

Ext.extend(Org.CouncilGroupToCouncilPanel, Ext.Panel, {

	searchForm: null,

	elementId: 0,

	elementCombo: null,

	associatedStore: null,

	associatedPaging: null,

	associatedGrid: null,

	associatedDD: null,

	nonAssociatedStore: null,

	nonAssociatedPaging: null,

	nonAssociatedGrid: null,

	nonAssociatedDD: null,

	waitDlg: null,

	initComponent: function() {

		this.layout = 'border';
		this.title = MSG['councilgroup.council.title'];
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-councilgroup-find';


		this.elementCombo = new Org.CouncilGroupCombo({
			hiddenName: 'id',
			organization: Main.app.getUser().organization
		});
		this.elementCombo.on("select", this.onChangeSelection, this);

		// Form panel
		this.searchForm = new Ext.FormPanel({
			region: 'north',
			height: 35,
			margins: '5',
			labelWidth: 200,
			bodyStyle: 'padding: 5px 5px 5px 20px',
			items: [this.elementCombo]
		});

		// Associated store
		this.associatedStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/associated.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			fields: ['id', 'name', 'province']
		});

		// Associated paging
		this.associatedPaging = new Ext.PagingToolbar({
			store: this.associatedStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin('')]
		});

		// Associated grid
		this.associatedGrid = new Ext.grid.GridPanel({
			title: MSG['councilgroup.council.associated'],
			anchor: '49% 100%',
			ddGroup: 'nonassociatedDD',
			enableDragDrop: true,
			cls: 'left',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				{header: MSG['council.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['council.name'], dataIndex: 'name', width: 140, sortable: true},
				{header: MSG['council.province'], dataIndex: 'province', width: 200, sortable: true}
			]),
			store: this.associatedStore,
			bbar: this.associatedPaging,
			listeners: {
				render: {
					fn: this.setupAssociatedDnD,
					scope: this
				}
			}
		});

		// Non associated store
		this.nonAssociatedStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/councilgroup/nonassociated.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			fields: ['id', 'name', 'province']
		});

		// Non associated paging
		this.nonAssociatedPaging = new Ext.PagingToolbar({
			store: this.nonAssociatedStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin('')]
		});

		// Non associated grid
		this.nonAssociatedGrid = new Ext.grid.GridPanel({
			title: MSG['councilgroup.council.nonassociated'],
			anchor: '49% 100%',
			ddGroup: 'associatedDD',
			enableDragDrop: true,
			cls: 'right',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				{header: MSG['council.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['council.name'], dataIndex: 'name', width: 140, sortable: true},
				{header: MSG['council.province'], dataIndex: 'province', width: 200, sortable: true}
			]),
			store: this.nonAssociatedStore,
			bbar: this.nonAssociatedPaging,
			listeners: {
				render: {
					fn: this.setupNonAssociatedDnD,
					scope: this
				}
			}
		});


		this.items = [this.searchForm, {
			xtype: 'panel',
			region: 'center',
			layout: 'anchor',
			items: [this.associatedGrid, this.nonAssociatedGrid]
		}];


		Org.CouncilGroupToCouncilPanel.superclass.initComponent.call(this);
	},

	setupAssociatedDnD: function() {
		var thePanel = this;
		var associatedEl =  this.associatedGrid.getView().el.dom.childNodes[0].childNodes[1];
		this.associatedDD = new Ext.dd.DropTarget(associatedEl, {
			ddGroup: 'associatedDD',
			copy: true,
			notifyDrop: function(ddSource, e, data){

				var theCouncils = [];
				var i = 0;
				for(; i < data.selections.length; ++i) {
					theCouncils.push(data.selections[i].get('id'));
				}

				Ext.Ajax.request({
					waitTitle: MSG['wait.title'],
					waitMsg: MSG['wait.message'],
					url: CONTEXT_PATH + "/secure/orgadmin/councilgroup/addcouncil.json",
					scope: thePanel,
					params: { id: thePanel.elementId, councils: theCouncils },
					success: function() {
						thePanel.associatedPaging.onClick("refresh");
						thePanel.nonAssociatedPaging.onClick("refresh");
					},
					failure: function() {
				 		notifyError(MSG['error'], MSG['error.message']);
					}
				});

				return (true);
			}
		});
	},

	setupNonAssociatedDnD: function() {
		var thePanel = this;
		var nonAssociatedEl = this.nonAssociatedGrid.getView().el.dom.childNodes[0].childNodes[1];
		this.nonAssociatedDD = new Ext.dd.DropTarget(nonAssociatedEl, {
			ddGroup: 'nonassociatedDD',
			copy: false,
			notifyDrop : function(ddSource, e, data){

				var theCouncils = [];
				var i = 0;
				for(; i < data.selections.length; ++i) {
					theCouncils.push(data.selections[i].get('id'));
				};

				Ext.Ajax.request({
					waitTitle: MSG['wait.title'],
					waitMsg: MSG['wait.message'],
					url: CONTEXT_PATH + "/secure/orgadmin/councilgroup/removecouncil.json",
					scope: thePanel,
					params: { id: thePanel.elementId, councils: theCouncils },
					success: function() {
						thePanel.associatedPaging.onClick("refresh");
						thePanel.nonAssociatedPaging.onClick("refresh");
					},
					failure: function() {
						notifyError(MSG['error'], MSG['error.message']);
					}
				});
				return (true);
			}
		});


	},

	onChangeSelection: function(combo, record/*, index*/) {
		this.elementId = record.data.id;
		var parameters = { id: this.elementId };
		this.associatedStore.baseParams = parameters;
		this.associatedPaging.doLoad(0);
		this.nonAssociatedStore.baseParams = parameters;
		this.nonAssociatedPaging.doLoad(0);
	}

});




/**
 * Module definition.
 */
MODULES['6_councilgroups'] = {

	menu: null,

	init: function() {
		// Initialize common menu
		this.menu = new Ext.menu.Menu({
			items: [{
				text: MSG['councilgroup.search'],
				iconCls: 'icon-councilgroup-find',
				handler: this.onFindCouncilGroup,
				scope: this
			},{
				text: MSG['councilgroup.new'],
				iconCls: 'icon-councilgroup-add',
				handler: this.onEditCouncilGroup,
				scope: this
			},{
				text: MSG['councilgroup.council.title'],
				iconCls: 'icon-councilgroup-council',
				handler: this.onAssociate,
				scope: this
			}, {
				text: MSG['check.groups.without.councils'],
				iconCls: 'icon-checks',
				handler: this.onCheckGroups,
				scope: this
			}, {
				text: MSG['check.councils.without.group'],
				iconCls: 'icon-checks',
				handler: this.onCheckCouncils,
				scope: this
			}]
		});


		// Add menu to toolbar
		Main.app.mainToolbar.add({
			text: MSG['councilgroups.title'],
			iconCls: 'icon-councilgroup',
			menu: this.menu
		});
	},

	onEditCouncilGroup: function() {
		var dialog = new Org.CouncilGroupDialog();
		dialog.show();
	},

	onFindCouncilGroup: function() {
		var panel = new Org.CouncilGroupSearchPanel();
		Main.app.addPanel(panel);
	},

	onAssociate: function() {
		var panel = new Org.CouncilGroupToCouncilPanel();
		Main.app.addPanel(panel);
	},

	onCheckGroups: function() {
		var panel = new Common.CheckPanel({
			title: MSG['check.groups.without.councils'],
			emptyText: MSG['no.groups.without.councils'],
			checkName: 'councilgroups',
			iconCls: 'icon-checks',
			storeFields: ['id', 'name'],
			columns: [{
				header: MSG['councilgroup.id'], dataIndex: 'id', width: 30, sortable: true
			},{
				header: MSG['councilgroup.name'], dataIndex: 'name', width: 100, sortable: true
			}]
		});
		Main.app.addPanel(panel);
	},

	onCheckCouncils: function() {
		var panel = new Common.CheckPanel({
			title: MSG['check.councils.without.group'],
			emptyText: MSG['no.councils.without.group'],
			checkName: 'councils',
			iconCls: 'icon-checks',
			storeFields: ['id', 'code', 'name', 'province'],
			columns: [{
				header: MSG['council.id'], dataIndex: 'id', width: 30, sortable: true
			},{
				header: MSG['council.code'], dataIndex: 'code', width: 60, sortable: true
			},{
				header: MSG['council.name'], dataIndex: 'name', width: 130, sortable: true
			},{
				header: MSG['council.province'], dataIndex: 'province', width: 100, sortable: true
			}]
		});
		Main.app.addPanel(panel);
	}

};
